/* jshint esversion: 6 */
$(function() {
  // 向页面添加背景蒙版
  const $modalBackdrop = $("<div class=\"modal-backdrop fade\"></div>");
  $("body").append($modalBackdrop);

  const fnModalBackdropToggle = function(action) {
    if (action === "show") {
      $modalBackdrop.fadeIn("fast").addClass("in");
    } else {
      $modalBackdrop.removeClass("in").fadeOut("slow");
    }
  };

  const fnModal = function(action, $target = null) {
    if (action === "show" && $target.length > 0) {
      fnModalBackdropToggle("show");
      $(".target-bar").addClass("active").removeClass("remove");
      $target.addClass("active").siblings().removeClass("active");
    } else {
      fnModalBackdropToggle("hide");
      $(".target-bar").addClass("remove");
    }
  };

  $modalBackdrop.click(function() {
    fnModal("hide");
  });

  // act-bar 按钮点击事件
  $(".act-bar a.act").click(function() {
    let target = $(this).data("target");
    let $target = $(`.target.${target}`);
    if ("like" === target) {
      return;
    }
    $(".wechat-qrcode").addClass("remove");
    fnModal("show", $target);
  });

  $(".target.share a")
    .mouseenter(function() {
      $(this).find("i").addClass("fadeInDown animated");
    })
    .mouseleave(function() {
      $(this).find("i").removeClass("fadeInDown animated");
    });

  $(".wechat-link").click(function() {
    if (!$(this).data("done")) {
      $(".wechat-qrcode").addClass("active").removeClass("remove");
      $(this).data("done", 1);
      let $qr = $(".wechat-qrcode .qrcode");
      let url = $qr.attr("title");

      $qr.qrcode({
        render: "canvas",
        size: 137,
        minVersion: 1,
        ecLevel: "M",
        text: url,
      });
    } else {
      $(".wechat-qrcode").toggleClass("remove");
    }
  });

  // 自动弹出赞助提示
  let intVisit = parseInt(zbp.cookie.get("MizuJS_Visit")) || 1;
  let bolSkipDSAuto = zbp.cookie.get("MizuJS_SkipDSAuto") === "true";
  let isBoxShowed = false;
  // console.log(intVisit, isBoxShowed, bolSkipDSAuto);
  const fnSaveCookie = function() {
    zbp.cookie.set("MizuJS_Visit", intVisit, 365);
    zbp.cookie.set("MizuJS_SkipDSAuto", bolSkipDSAuto ? "true" : "false", 365);
  };

  // 切换回窗口时自动弹出赞助提示，只弹一次
  $(window).focus(function() {
    // console.log(intVisit, isBoxShowed, bolSkipDSAuto);
    if (isBoxShowed) {
      return;
    }
    if (intVisit % 4 === 0 && !bolSkipDSAuto) {
      fnModal("show", $(".target.donate"));
      isBoxShowed = true;
    }
    intVisit += 1;
  });

  // 每次访问 +1 并保存
  intVisit += 1;
  fnSaveCookie();

  // 设置当前的开关状态
  $("#skip_donate_auto").prop("checked", bolSkipDSAuto);
  // 开关状态改变时保存
  $("#skip_donate_auto").on("change", function() {
    bolSkipDSAuto = $(this).is(":checked");
    fnSaveCookie();
  });

});
